package com.train.trainmanage.controller;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.train.trainmanage.model.ComeGoDirectionModel;
import com.train.trainmanage.model.DailyPlanTrainModel;
import com.train.trainmanage.model.RelationDirectionModel;
import com.train.trainmanage.model.StationModel;
import com.train.trainmanage.model.TrackModel;
import com.train.trainmanage.model.UserModel;
import com.train.trainmanage.service.ComeGoDirectionService;
import com.train.trainmanage.service.DailyPlanTrainService;
import com.train.trainmanage.service.RelationDirectionService;
import com.train.trainmanage.service.StationService;
import com.train.trainmanage.service.TrackService;
import com.train.trainmanage.util.ExcelUtil;


@Controller
@RequestMapping("/dailyPlan")
public class DailyPlanTrainController {
	private static final Logger logger = LoggerFactory.getLogger(DailyPlanTrainController.class);
	@Autowired
	private DailyPlanTrainService dailyPlanService;
	@Autowired
	private StationService stationService;
	@Autowired
	private TrackService trackService;
	@Autowired 
	private ComeGoDirectionService comeGoService;
	@Autowired
	private RelationDirectionService relationDirectionService;
	
	
	@RequestMapping("/workList")
	public ModelAndView workList(HttpServletRequest request, HttpServletResponse response,DailyPlanTrainModel train,Integer workTrainId) throws IOException, ParseException {
		ModelAndView mav = new ModelAndView();
		HttpSession session = request.getSession();
		UserModel user = (UserModel) session.getAttribute("user");
		logger.info("操作员---" + user.getUserName() + "----进入工作台页面");
		List<DailyPlanTrainModel> trainList = dailyPlanService.listByTrainModel(train);
		List<StationModel> stationList = stationService.getAllStation();
		
		if(trainList != null && trainList.size()>0) {
			DailyPlanTrainModel firstTrain = new DailyPlanTrainModel();
			if(workTrainId != null && workTrainId > 0) {
				firstTrain = dailyPlanService.getInfoById(workTrainId);
			}else {
				//展示第一个车次的信息
				firstTrain = trainList.get(0);
				firstTrain = dailyPlanService.getInfoById(firstTrain.getId());
			}
			List<TrackModel> trackList = trackService.listAllTrack();
			
			ComeGoDirectionModel comeDirec = comeGoService.getByDirecid(firstTrain.getComeDirectionId());
			ComeGoDirectionModel goDirec = comeGoService.getByDirecid(firstTrain.getGoDirectionId());
			
			mav.addObject("firstTrain", firstTrain);
			mav.addObject("trackList",trackList);
			
			mav.addObject("comeDirec", comeDirec);
			mav.addObject("goDirec", goDirec);
		}
		
		mav.addObject("train", train);
		mav.addObject("trainList", trainList);
		mav.addObject("stationList", stationList);
		
		if(user.getRole() == 1) {
			mav.setViewName("/train/work");
		}else if(user.getRole() == 3) {
			mav.setViewName("/train/workLook");
		}
		return mav;
	}
	
	@RequestMapping("/workSave")
	 public @ResponseBody Map<String, Object> workSave(HttpServletRequest request, HttpServletResponse response,DailyPlanTrainModel train,
			 String reachTimeStr,String leaveTimeStr) throws ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		try{
			if(reachTimeStr != null && !"".equals(reachTimeStr)) {
				train.setReachTime(sdf.parse(reachTimeStr));
			}
			if(leaveTimeStr != null && !"".equals(leaveTimeStr)) {
				train.setLeaveTime(sdf.parse(leaveTimeStr));
			}
		}catch(ParseException e) {
			e.printStackTrace();
		}
		if(train != null) {
			Integer comeDirectionId = train.getComeDirectionId();
			Integer goDirectionId = train.getGoDirectionId();
			Integer pickUpTrack = train.getPickUpTrack();
			train.setDepartureTrack(pickUpTrack);
			
			Map<String, Object> map2 = new HashMap<String, Object>();
			map2.put("comeId", comeDirectionId);
			map2.put("goId", 0);
			RelationDirectionModel comeDirection = relationDirectionService.getByMap(map2);
			if(comeDirection != null) {
				String ableTrackString = comeDirection.getAbleTrace();
				if(ableTrackString != null && !ableTrackString.contains(pickUpTrack.toString())) {
					map.put("success", false);
					map.put("message", "所选来车方向，股道不匹配，请确认后再保存");
					return map;
				}
			}
			map2.clear();
			map2.put("comeId", comeDirectionId);
			map2.put("goId", goDirectionId);
			RelationDirectionModel goDirection = relationDirectionService.getByMap(map2);
			if(goDirection != null) {
				String ableTrackString = goDirection.getAbleTrace();
				if(ableTrackString != null && !ableTrackString.contains(pickUpTrack.toString())) {
					map.put("success", false);
					map.put("message", "所选发车方向，股道不匹配，请确认后再保存");
					return map;
				}
			}  
			TrackModel track = trackService.getByTrackId(pickUpTrack);
			Integer isAddWater = train.getIsAddWater();
			Integer isDealRubbish = train.getIsDealRubbish();
			if(track != null && track.getIsAddWater() != null) {
				if("1".equals(isAddWater.toString()) && !"1".equals(track.getIsAddWater().toString())) {
					map.put("success", false);
					map.put("message", "所选股道不支持上水，请确认后再保存");
					return map;
				}
			}
			if(track != null && track.getIsDealRubbish() != null) {
				if("1".equals(isDealRubbish.toString()) && !"1".equals(track.getIsDealRubbish().toString())) {
					map.put("success", false);
					map.put("message", "所选股道不支持去污，请确认后再保存");
					return map;
				}
			}
			
			Integer result = dailyPlanService.saveDailyPlanTrain(train);
			if(result > 0) {
				map.put("success", true);
				map.put("message", "保存成功");
			}else {
				map.put("success", false);
				map.put("message", "保存失败");
			}
		}else {
			map.put("success", false);
			map.put("message", "保存失败");
		}
		
		return map;
	}
	
	
	@RequestMapping("/workLookList")
	public ModelAndView workLookList(HttpServletRequest request, HttpServletResponse response,DailyPlanTrainModel train,
			String reachTimeStr,String leaveTimeStr) throws IOException, ParseException {
		ModelAndView mav = new ModelAndView();
		HttpSession session = request.getSession();
		UserModel user = (UserModel) session.getAttribute("user");
		logger.info("客运工作人员---" + user.getUserName() + "----进入工作台页面");
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		if(reachTimeStr != null && reachTimeStr.length() >0) {
			train.setReachTime(sdf.parse(reachTimeStr));
		}
		if(leaveTimeStr != null && leaveTimeStr.length() >0) {
			train.setLeaveTime(sdf.parse(leaveTimeStr));
		}
		
		List<DailyPlanTrainModel> trainList = dailyPlanService.listByTrainModel(train);
		
		if(trainList != null && trainList.size()>0) {
			for(DailyPlanTrainModel temModel : trainList) {
				DailyPlanTrainModel temModel2 = dailyPlanService.getInfoById(temModel.getId());
				temModel.setStartStationName(temModel2.getStartStationName());
				temModel.setEndStationName(temModel2.getEndStationName());
				temModel.setComeDirectionName(temModel2.getComeDirectionName());
				temModel.setGoDirectionName(temModel2.getGoDirectionName());
			}
		}
		
		List<TrackModel> trackList = trackService.listAllTrack();
		List<StationModel> stationList = stationService.getAllStation();
		
		mav.addObject("train", train);
		mav.addObject("trackList",trackList);
		mav.addObject("trainList", trainList);
		mav.addObject("stationList", stationList);
		
		mav.setViewName("/train/workLook");
		return mav;
	}
	
	
	/*@RequestMapping("/getInfo4Work")
    public @ResponseBody Map<String, Object> getInfo4Work(HttpServletRequest request, HttpServletResponse response,Integer trainId) throws ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		if(trainId != null && trainId >0) {
			DailyPlanTrainModel train = dailyPlanService.getInfoById(trainId);
			
			List<TrackModel> pickUpTrackList = new ArrayList<TrackModel>(); //接车股道
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
			String stareTimeStr = sdf.format(train.getStartTime());
			Date startTime = (Date) sdf.parse(stareTimeStr);
			train.setStartTime(startTime);
			Map<String, Object> map2 = new HashMap<String,Object>();
			if(train.getComeDirectionId() != null) {
				   map2.put("comeId", train.getComeDirectionId());
				   map2.put("goId", 0);
				   RelationDirectionModel directionModel = relationDirectionService.getByMap(map2);
				   if(directionModel != null) {
					   String ableTrace = directionModel.getAbleTrace();
					   List<String> trackIdList = Arrays.asList(ableTrace.split(","));
					   if(trackIdList != null && trackIdList.size() >0) {
						   for(String temId : trackIdList) {
							   TrackModel track = trackService.getByTrackId(Integer.valueOf(temId));
							   pickUpTrackList.add(track);
						   }
					   }
				   }
			}
			
			List<TrackModel> departureTrackList = new ArrayList<TrackModel>(); //发车股道
			Map<String, Object> map3 = new HashMap<String,Object>();
			if(train.getComeDirectionId() != null && train.getGoDirectionId() != null) {
				   map3.put("comeId", train.getComeDirectionId());
				   map3.put("goId", train.getGoDirectionId());
				   RelationDirectionModel directionModel = relationDirectionService.getByMap(map3);
				   if(directionModel != null) {
					   String ableTrace = directionModel.getAbleTrace();
					   List<String> trackIdList = Arrays.asList(ableTrace.split(","));
					   if(trackIdList != null && trackIdList.size() >0) {
						   for(String temId : trackIdList) {
							   TrackModel track = trackService.getByTrackId(Integer.valueOf(temId));
							   departureTrackList.add(track);
						   }
					   }
				   }
			}
			
			ComeGoDirectionModel comeDirec = comeGoService.getByDirecid(train.getComeDirectionId());
			ComeGoDirectionModel goDirec = comeGoService.getByDirecid(train.getGoDirectionId());
			
			map.put("train", train);
			map.put("pickUpTrackList", pickUpTrackList);
			map.put("departureTrackList", departureTrackList);
			map.put("comeDirec", comeDirec);
			map.put("goDirec", goDirec);
			map.put("success", true);
		}else {
			map.put("success", false);
		}
	   
	   return map;
	}
	*/
	
	@RequestMapping("/deleteAll")
	public @ResponseBody Map<String, Object> deleteAll(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
		   Map<String, Object> map = new HashMap<String, Object>();
		   HttpSession session = httpRequest.getSession();
		   UserModel user = (UserModel) session.getAttribute("user");
		   logger.info("操作员---" + user.getUserName() + "----删除旧的日计划");
		   int result = dailyPlanService.delOldDailyPlan();
		   if(result >0) {
			   	map.put("success", true);
				map.put("message", "删除成功~");
		   }else {
			   map.put("success", false);
			   map.put("message", "删除失败，请重试！");
		   }
		   return map;
	}
	
	
	
	@RequestMapping("/fileUpload")
	public @ResponseBody Map<String, Object> fileUpload(HttpServletRequest request, HttpServletResponse httpResponse,@RequestParam("file") MultipartFile file){
		long  startTime=System.currentTimeMillis();
		Map<String, Object> map = new HashMap<String, Object>();
		HttpSession session = request.getSession();
		UserModel user = (UserModel) session.getAttribute("user");
		logger.info("操作员---" + user.getUserName() + "----上传新的日计划");
		if(file != null) {
			String fileName = file.getOriginalFilename(); //文件的原名
			String type = file.getContentType();
			logger.info("fileName====" + fileName + "************* fileType====="  + type+"*********  name==="+file.getName());
			Workbook wb = null;
			
			try {
				InputStream in = file.getInputStream();
				if(fileName.endsWith(".xls")){     //Excel2003
					wb = new HSSFWorkbook(in);
				}else if(fileName.endsWith(".xlsx")){    // Excel2007/2010
					wb = new XSSFWorkbook(in);
				}else {
					map.put("success", false);
					map.put("message", "请上传excle文件");
					return map;
				}
				
				List<DailyPlanTrainModel> dailyPlanTrainList = ExcelUtil.createDailyPlan(wb);
				if(dailyPlanTrainList != null && dailyPlanTrainList.size() > 0) {
					Integer n = dailyPlanService.saveByExcle(dailyPlanTrainList);
					if(n >0) {
						map.put("success", true);
						map.put("message", "上传成功");
					}else {
						map.put("success", false);
						map.put("message", "上传失败,请稍后重试...");
					}
				}
				
			} catch (IOException e) {
				e.printStackTrace();
				map.put("success", false);
				map.put("message", e.getMessage());
				return map;
			}
			
		}else {
			map.put("success", false);
			map.put("message", "请上传文件");
			return map;
		}
    
		long  endTime=System.currentTimeMillis();
		System.out.println("方法运行时间："+String.valueOf(endTime-startTime)+"ms");
		return map;
	}
	
	
	
	
	
}
